import { ref, onUnmounted } from 'vue'

export function useWebSocket(url, onMessage, onOpen, onClose) {
    const socket = ref(null)
    const isConnected = ref(false)

    // 连接WebSocket
    const connect = (newUrl = url) => {

        // 如果已有连接，先关闭
        if (socket.value) {
            socket.value.close()
        }

        socket.value = new WebSocket(newUrl)

        // 连接打开时
        socket.value.onopen = (event) => {
            isConnected.value = true
            if (onOpen) onOpen(event)
        }

        // 收到消息时
        socket.value.onmessage = (event) => {
            if (onMessage) onMessage(event)
        }

        // 连接关闭时
        socket.value.onclose = (event) => {
            isConnected.value = false
            if (onClose) onClose(event)
        }

        // 发生错误时
        socket.value.onerror = (error) => {
            console.error('WebSocket错误:', error)
            isConnected.value = false
        }
    }

    // 发送消息
    const sendMessage = (data) => {
        if (socket.value && isConnected.value) {
            try {
                socket.value.send(JSON.stringify(data))
                return true
            } catch (error) {
                console.error('发送消息失败:', error)
                return false
            }
        }
        return false
    }

    // 关闭连接
    const close = () => {
        if (socket.value) {
            socket.value.close()
            socket.value = null
            isConnected.value = false
        }
    }

    // 组件卸载时关闭连接
    onUnmounted(() => {
        close()
    })

    return {
        socket,
        isConnected,
        connect,
        sendMessage,
        close
    }
}
